import React, { useState, Fragment } from "react";

// import styled from "styled-components";
import { Form, Select } from "@arco-design/web-react/icon";

import { renderFormItem } from "./../render";
import { PropertyType } from "../../../consts";
import { useEffect } from "react";

// export const FormItemWrapper = styled.div`
// 	& .ant-form-item {
// 		margin-bottom: 5px;
// 	}
// `;

const SelectIndex = ({ cItem, cData }) => {
	// const [selectItem, setSelectItem] = useState(cItem);
	const contentDataType = cData?.dataSource?.contentDataType;
	const [opValue, setOpValue] = useState(contentDataType); // cItem.default
	const contentDataSource = cData?.dataSource;
	// console.log("cData= ", cItem, cData);

	const loopChild = (item, data) => {
		return (
			item.children &&
			item.children.map((aItem, aIndex) => {
				// 如果contentDataSource 不为空说明是父层级，为空说明是子层级
				// console.log(aItem.name, data, aItem, data[aItem.name]);
				// console.log("aItem= ", aItem, cData);
				return (
					<Fragment key={`aItem-${aIndex}`}>
						{data
							? aItem.type === PropertyType.ArrayType || aItem.type === PropertyType.Data
								? renderFormItem[aItem.type]?.(aItem, data[aItem.name]) // data[aItem.name]
								: renderFormItem[aItem.type]?.(aItem)
							: renderFormItem[aItem.type]?.(aItem)}
					</Fragment>
				);
			})
		);
	};

	const renderSelectChild = (selectItem, opValue) => {
		const item = selectItem.value[opValue];

		if (item === undefined) return <></>;

		return loopChild(item, contentDataSource);
	};

	useEffect(() => {
		setOpValue(contentDataSource ? contentDataType : cData);
	});

	return (
		<>
			<Form.Item hidden={cItem.hidden} label={cItem.label} name={cItem.name} field={cItem.name}>
				<Select
					options={cItem.value}
					onChange={value => {
						setOpValue(value);
					}}
				/>
			</Form.Item>
			{renderSelectChild(cItem, opValue)}
		</>
	);
};

export default SelectIndex; // memo(Index);
